/** @file    AlarmEngine.cpp
 *  @author  Alessandro Polo
 *  @version $Id: AlarmEngine.cpp 2612 2010-05-29 16:03:23Z alex $
 *  @brief
 * File containing methods for the wosh::security::AlarmEngine class.
 * The header for this class can be found in AlarmEngine.h, check that file
 * for class description.
 ****************************************************************************/
/* Copyright (c) 2007-2010, WOSH - Wide Open Smart Home 
 * by Alessandro Polo - OpenSmartHome.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSmartHome.com WOSH nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY Alessandro Polo ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Alessandro Polo BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ****************************************************************************/

 #include <framework/security/AlarmEngine.h>
 #include <core/Message.h>

 #include <stdlib.h>
 #include <time.h>

using namespace std;
namespace wosh {
 namespace security {

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////// CONSTRUCTORS

AlarmEngine::AlarmEngine() : ThreadImpl(NULL, "wosh::services::Alarm.Thread")
 {
	this->listener = NULL;

	Log.setIndent( 3 );
	Log.setContext( "AlarmEngine" );
	Log.setLevel( LOG_INFO );

//Log.setLevel( VERBOSE );

	this->alarmState = new AlarmState();
	this->alarmState->setListener(this);

	this->alarmBrain = new AlarmBrain();
	this->alarmBrain->setListener(this);
 }

AlarmEngine::~AlarmEngine() {
	Log(LOG_VERBOSE, ":~AlarmEngine() Destroying.." );
	if ( isThreadRunning() ) {
		quitThread(10000);
	 }

	Log(LOG_VERBOSE, ":~AlarmEngine() Destroying AlarmBrain.." );
	delete this->alarmBrain; this->alarmBrain = NULL;
	Log(LOG_VERBOSE, ":~AlarmEngine() Destroying AlarmState.." );
	delete this->alarmState; this->alarmState = NULL;
 }

//////////////////////////////////////////////////////////////////////////////////////////////// CONSTRUCTORS
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////// RUN THREAD

void AlarmEngine::runThread()
 {
	Log(LOG_VERBOSE, ":runThread(): STARTING" );

	if ( this->listener != NULL )
		this->listener->alarm_armed( this );

	while( this->running )
	 {
		ThreadImpl::sleepForMSec(100);
		setThreadAlive();
		if ( this->msgQueue.isEmpty() ) {
			ThreadImpl::sleepForMSec(150);
			continue;
		 }

		// get and remove it from queue
		Message* message = this->msgQueue.pop();
		if ( message == NULL ) continue;

		Log(LOG_VERBOSE, " MSG %"PRId64" %s->[%s]%s | %s", message->getID(), 
				message->getSource().toString().c_str(), message->getDestinationBus().c_str(), message->getDestination().toString().c_str(),
				message->getContentClassName().c_str()	);

		this->alarmTriggers.transactionBeginRead();
		tAlarmTriggerList::Iterator it;
		const tAlarmTriggerList::ConstIterator it_end = this->alarmTriggers.end();
		for ( it=this->alarmTriggers.begin(); it!=it_end; ++it ) {
			if ( *it == NULL ) continue;
			if ( !(*it)->isEnabled() ) continue;
			long val = (*it)->evaluateMessage( message, this->alarmState );
			this->alarmBrain->evaluateState( this->alarmState, val );
		 }
		this->alarmTriggers.transactionEnd();

		// finally delete the instance
		delete message;
	 }

	if ( this->listener != NULL )
		this->listener->alarm_disarmed( this );

	Log(LOG_VERBOSE, ":runThread(): EXITING" );
 }

////////////////////////////////////////////////////////////////////////////////////////////////// RUN THREAD
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

WRESULT AlarmEngine::arm( unsigned long timeout ) {
	return this->startThread(timeout);
 }

WRESULT AlarmEngine::disarm( unsigned long timeout ) {
	return this->quitThread(timeout);
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

WRESULT AlarmEngine::evalMessage( const Message& message ) {
	if ( this->alarmTriggers.size() == 0 )
		return WRET_ERR_PARAM;

	this->msgQueue.push_back( message.clone() );
	return WRET_OK;
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

WRESULT AlarmEngine::addTrigger( AlarmTrigger* trigger ) {
	if ( trigger == NULL ) return WRET_ERR_PARAM;

	Log(LOG_VERBOSE, ":addTrigger() ID#%ld", trigger->getID() );

	this->alarmTriggers.append(trigger);
	return WRET_OK;
 }

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////// BRAIN EVENTS

void AlarmEngine::raised_AlarmBrain_Error( int error, const std::string& description, AlarmBrain* brain ) {
	Log(LOG_VERBOSE, ":raised_AlarmBrain_Error(): " );

	//forward the event
	if ( this->listener == NULL )
		return;
	this->listener->raised_AlarmBrain_Error( error, description, brain );
 }

//////////////////////////////////////////////////////////////////////////////////////////////// BRAIN EVENTS
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////// STATE EVENTS

void AlarmEngine::changed_AlarmState( int state, AlarmState* alarm_state )
 {
	//forward the event
	if ( this->listener == NULL )
		return;
	this->listener->changed_AlarmState( state, alarm_state );
 }

void AlarmEngine::raised_AlarmEvent( const AlarmEvent* alarm_event, AlarmState* alarm_state )
 {
	//forward the event
	if ( this->listener == NULL )
		return;
	this->listener->raised_AlarmEvent( alarm_event, alarm_state );
 }

//////////////////////////////////////////////////////////////////////////////////////////////// STATE EVENTS
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

 }; // namespace security
}; // namespace wosh
